package com.ruoyi.order.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.order.domain.PrintOrder;
import com.ruoyi.order.mapper.PrintOrderMapper;
import com.ruoyi.order.service.PrintOrderService;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.UUID;

@Service
public class PrintOrderServiceImpl implements PrintOrderService {

    @Resource
    private PrintOrderMapper printOrderMapper;

    @Override
    public Long createOrder(PrintOrder order) {
        Assert.notNull(order, "order is null");
        if (order.getPayAmount() == null) {
            order.setPayAmount(order.getTotalAmount() == null ? BigDecimal.ZERO : order.getTotalAmount());
        }
        order.setOrderNo(genOrderNo());
        order.setStatus("pending");
        order.setDelFlag("0");
        order.setCreateTime(new Date());
        int rows = printOrderMapper.insert(order);
        if (rows <= 0) {
            throw new ServiceException("创建订单失败");
        }
        return order.getId();
    }

    @Override
    public PageInfo<PrintOrder> pageList(PrintOrder query, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<PrintOrder> list = printOrderMapper.selectList(query);
        return new PageInfo<>(list);
    }

    @Override
    public PrintOrder detail(Long id, Long userId) {
        PrintOrder db = printOrderMapper.selectById(id);
        if (db == null || !db.getUserId().equals(userId)) {
            throw new ServiceException("订单不存在");
        }
        return db;
    }

    @Override
    public boolean cancel(Long id, Long userId) {
        PrintOrder db = detail(id, userId);
        if (!"pending".equals(db.getStatus())) {
            throw new ServiceException("订单状态不允许取消");
        }
        db.setStatus("cancelled");
        db.setUpdateTime(new Date());
        return printOrderMapper.updateById(db) > 0;
    }

    @Override
    public boolean mockPay(Long id, Long userId) {
        PrintOrder db = detail(id, userId);
        if (!"pending".equals(db.getStatus())) {
            throw new ServiceException("订单状态不允许支付");
        }
        db.setStatus("paid");
        db.setPayTime(new Date());
        db.setUpdateTime(new Date());
        return printOrderMapper.updateById(db) > 0;
    }

    private String genOrderNo() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 16).toUpperCase();
    }
} 